package com.itheima.web.servlet;

import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
    private UserService us = new UserServiceImpl();
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            req.setCharacterEncoding("utf-8");
            String method = req.getParameter("method");
            Class clazz = this.getClass();
            Method clazzMethod = clazz.getMethod(method, HttpServletRequest.class, HttpServletResponse.class);
            clazzMethod.invoke(this, req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        } 


    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
    
    public void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, String[]> map = req.getParameterMap();
        User user = new User();
        try {
            BeanUtils.populate(user,map);
        } catch (Exception e) {
            e.printStackTrace();
        }


        User uus = us.login(user);

        if(uus==null){
            req.setAttribute("msg","登陆失败");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
            return;
        } else{
            req.getSession().setAttribute("uus",uus);
            resp.sendRedirect(req.getContextPath()+"/index.jsp");
        }


    }


    public void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        List<User> userList = us.list();
        req.setAttribute("list",userList);
        req.getRequestDispatcher("/list.jsp").forward(req,resp);
    }


    public void addUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        Map<String, String[]> map = req.getParameterMap();
        User user = new User();
        try {
            BeanUtils.populate(user,map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        us.addUser(user);
        resp.sendRedirect(req.getContextPath()+"/userServlet?method=list");
    }
    
    


}
